package com.fang.transfer.file.client.connection;

import com.fang.transfer.file.client.AppContext;
import com.google.gson.Gson;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class UdpUtil {

    public final static byte HOLD = 1;

    private final DatagramSocket socket;
    public volatile static int PACKAGE_LENGTH = 35507;


    public UdpUtil() throws Exception {
        // 1.创建服务器端DatagramSocket，指定端口
        this.socket = new DatagramSocket();
    }

    public void receive(DatagramPacket packet) throws IOException {
        this.socket.receive(packet);
    }



    public void sendServiceInfo(String code, Object dataObj) throws Exception {
        String jsonData = new Gson().toJson(dataObj);
        String data = code + jsonData;
        byte[] bytes = data.getBytes(AppContext.charsetName);
        String text = AppContext.gui.getHostText().getText();
        String[] serviceAddr = text.split(":");
        InetSocketAddress address = new InetSocketAddress(serviceAddr[0], Integer.parseInt(serviceAddr[1]) + 1);
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address);
        socket.send(packet);
    }

    /**
     * 发送目标用户信息
     *
     * @param data       数据内容
     * @param targetUser 目标用户
     */
    public void sendInfoTargetUser(InetSocketAddress targetUser, byte code, Object data) throws Exception {
        String json = new Gson().toJson(data);
        byte[] bytes = json.getBytes(AppContext.charsetName);
        byte[] sendData = new byte[bytes.length + 3];
        bytes[0] = -1;
        bytes[1] = -1;
        bytes[2] = code;

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, targetUser);
        socket.send(packet);
    }

    public void sendData(DatagramPacket packet) throws IOException {
        socket.send(packet);
    }

}
